package cn.com.spic.demo.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

/**
 * 返回值
 *
 * @author lipangeng, Email:lipg@outlook.com
 * @version v1.0.0
 * @since v1.0.0
 * Created on 2020/11/4 2:59 下午
 */
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements Serializable {
    /**
     * 跟踪Id，每个请求有唯一Id。
     */
    private String traceId;
    /**
     * 是否成功的唯一标示
     */
    private boolean success;
    /**
     * 时间戳,Unix Timestamp
     */
    private Date timestamp;
    /**
     * 状态码
     */
    private String code;
    /**
     * 说明消息
     */
    private String message;
    /**
     * 实际返回数据内容
     */
    private T data;
    /**
     * 异常数据内容，用于异常时需返回数据的情况
     */
    private Object failData;

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public void setFailData(Object failData) {
        this.failData = failData;
    }

    /**
     * 成功
     *
     * @since v1.0.0
     * Created by lipangeng. Email:lipg@outlook.com
     * Created on 2020/11/4 3:22 下午
     */
    public static <T> R<T> ofSuccess(T data) {
        R<T> r = new R<>();
        r.setTraceId(UUID.randomUUID().toString());
        r.setSuccess(Boolean.TRUE);
        r.setTimestamp(new Date());
        r.setCode("200");
        r.setMessage("Succeed!");
        r.setData(data);
        return r;
    }

    /**
     * 失败
     *
     * @since v1.0.0
     * Created by lipangeng. Email:lipg@outlook.com
     * Created on 2020/11/4 3:27 下午
     */
    public static <T> R<T> ofError(String code, String message, Object failData) {
        R<T> r = new R<>();
        r.setTraceId(UUID.randomUUID().toString());
        r.setSuccess(Boolean.TRUE);
        r.setTimestamp(new Date());
        r.setCode(code);
        r.setMessage(message);
        r.setFailData(failData);
        return r;
    }
}
